/**
 * Created by qmh on 2016/7/1.
 */

import React from 'react';
import {Form,Col,Input,Button,Collapse,Row,Modal,Select,Tree,TreeSelect} from 'antd';
import util from 'util';
import menus from 'menu';
import sys_dict from 'sys_dict';

var FormItem=Form.Item;
var Panel=Collapse.Panel;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;
const OptGroup = Select.OptGroup;

@Form.create()
class Search extends React.Component{
    constructor(props){
        super(props);
        const keys= ['0-0-0', '0-0-1'];
        this.state = {
            children:[],
            defaultExpandedKeys:keys,
            defaultSelectedKeys:keys,
            defaultCheckedKeys:keys,
            treeData:[]
        };
    }
    onCheck(info) {
        console.log('onCheck1', info);
    }
    onSelect(info) {
        console.log('selected', info);
    }
    componentDidMount() {
        let list=[];
        var {setFieldsValue} = this.props.form;
        // setFieldsValue( this.props.data);
        setFieldsValue( {orgno: "", orgname: "",parentorgno:""});
    }
    getTreeDom(childlist){
        if(!childlist){
            return;
        }
        let list=[];

        for(let i=0 ;i<childlist.length;i++){
            console.log("treekey"+childlist[i].id);
            list.push(<TreeNode title={childlist[i].text} key={childlist[i].id} >
                {this.getTreeDom(childlist[i].children)}
            </TreeNode>);
        }
        return list;
    }
    reset(e){
        e.preventDefault();
        this.props.form.resetFields();
        this.props.form.resetFields();
        var {setFieldsValue} = this.props.form;
        setFieldsValue( {orgno: "", orgname: "",parentorgno:""});
    }
    search(e){
        e.preventDefault();
        console.log('接受到表单值23',this.props.form.getFieldsValue());
        this.props.search(this.props.form.getFieldsValue());
    }
    handleChange(value){
        console.log(`selected ${value}`);
    }
    onChange(value, label, extra) {
        console.log("change"+value);
       // this.setState({ value });
    }
    onSelect(value, node, extra) {
        console.log("selec2t"+value);
        // this.setState({ value });
    }
    onLoadData(treeNode) {
        return new Promise((resolve) => {
            setTimeout(() => {
                const treeData = [...this.state.treeData];
                getNewTreeData(treeData, treeNode.props.eventKey, generateTreeNodes(treeNode), 2);
                this.setState({ treeData });
                resolve();
            }, 500);
        });
    }
    render(){
        const {getFieldProps} =this.props.form;
        const formItemLayout={
            labelCol:{span:8},
            wrapperCol:{span:14}
        };
        //234234w
        return(
          <Collapse defaultActiveKey={['1']}>
              <Panel header="机构信息查询" key="1">
                  <Form inline className="ant-advanced-search-form">
                      <Row>
                          <Col span={7}>
                              <FormItem label="机构代码：" {...formItemLayout}>
                                  <Input
                                      {...getFieldProps('orgno')}
                                  />
                              </FormItem>
                          </Col>
                          <Col span={7}>
                              <FormItem label="机构名称：" {...formItemLayout}>
                                  <Input
                                      {...getFieldProps('orgname')}
                                  />
                              </FormItem>
                          </Col>
                          <Col span={10}>
                              <FormItem label="所属机构：" >
                                  <TreeSelectDemo  form={this.props.form} propsname="parentorgno"  requestUrl="org010101.json"></TreeSelectDemo>
                              </FormItem>
                          </Col>
                      </Row>
                      <Row style={{textAlign:'center'}}>
                          <Button className="btnMarginRright" type="primary" htmlType="submit" onClick={this.search.bind(this)}>搜索</Button>
                          <Button  htmlType="submit" onClick={this.reset.bind(this)}>重置</Button>
                      </Row>
                  </Form>
              </Panel>
          </Collapse>
        );
    }
}

@Form.create()
class Edit extends React.Component{
    getValidateStatus(field) {
        const { isFieldValidating, getFieldError, getFieldValue } = this.props.form;

        if (isFieldValidating(field)) {
            return 'validating';
        } else if (!!getFieldError(field)) {
            return 'error';
        } else if (getFieldValue(field)) {
            return 'success';
        }
    }
    constructor(props){
        super(props);
        this.state={
            children:[],
            setvalue:function(){}
        };
    }
    componentDidMount() {
        let children = [];
        var diclist= util.getSysDict("orglevel");
        console.log("orglevel");
        console.log(diclist);
        for (let i = 0; i < diclist.length; i++) {
            children.push(<Option key={diclist[i].itemkey} >{diclist[i].itemval}</Option>);
        }
        this.setState({
            children:children
        });
        var {setFieldsValue} = this.props.form;
        var jsondata=this.props.data;
        setFieldsValue( jsondata);
    }
    render(){
        console.log("---->",this.props.isAdd)
        const formItemLayout={
            labelCol:{span:6},
            wrapperCol:{span:14}
        };

        const { getFieldProps, getFieldError, isFieldValidating } = this.props.form;
        const orgnoProps = getFieldProps('orgno', {
            rules: [
                { required: true,whitespace: true, message: '请输入机构代码' },
            ],
        });
        const orgnameProps = getFieldProps('orgname', {
            rules: [
                { required: true,whitespace: true, message: '请输入机构名称' },
            ],
        });
        const orglevelProps = getFieldProps('orglevel', {
            rules: [
                { required: true, min: 0, message: '请选择机构级别' },
            ],
        });
        const parentorgnoProps = getFieldProps('parentorgno', {
            rules: [
                { required: true, min: 0, message: '请选择上级机构' },
            ],
        });
        //sdfer3
        const parentorgnameProps = getFieldProps('parentorgname', {
            rules: [
                { message: '请输入名称' },
            ],
        });
        const lngProps = getFieldProps('lng', {
            rules: [
                { required: true, message: '请输入经度' },
            ],
        });
        const latProps = getFieldProps('lat', {
            rules: [
                { required: true, message: '请输入纬度' },
            ],
        });

        return(
            <Form horizontal form={this.props.form}>
                <FormItem label="机构代码"
                    {...formItemLayout}
                          hasFeedback
                          help={isFieldValidating('orgno') ? '校验中...' : (getFieldError('orgno') || []).join(', ')}>
                    <Input {...orgnoProps} placeholder="请输入机构代码" disabled={this.props.operation=="edit"}/>
                </FormItem>
                <FormItem label="机构名称"
                    {...formItemLayout}
                          hasFeedback
                          help={isFieldValidating('orgname') ? '校验中...' : (getFieldError('orgname') || []).join(', ')}>
                    <Input {...orgnameProps} placeholder="请输入机构名称" />
                </FormItem>
                <FormItem label="机构级别" {...formItemLayout}  hasFeedback
                  help={isFieldValidating('orglevel') ? '校验中...' : (getFieldError('orglevel') || []).join(', ')}>
                    <Select  {...orglevelProps} style={{ width: 120 }} placeholder="请选择机构级别"  style={{ width: '100%' }}>
                        {this.state.children}
                    </Select>
                </FormItem>
                <FormItem label="上级机构" {...formItemLayout}  >
                    <TreeSelectDemo {...parentorgnoProps} form={this.props.form} propsname="parentorgno"  requestUrl="org010101.json" operation={this.props.operation}></TreeSelectDemo>
                </FormItem>


                {!this.props.isAdd?<FormItem label="上级机构名称"
                    {...formItemLayout}
                          hasFeedback
                          help={isFieldValidating('parentorgname') ? '校验中...' : (getFieldError('parentorgname') || []).join(', ')}>
                    <Input {...parentorgnameProps}  disabled={true} />
                </FormItem>:null}
                <FormItem label="经度"
                    {...formItemLayout}
                          hasFeedback
                          help={isFieldValidating('lng') ? '校验中...' : (getFieldError('lng') || []).join(', ')}>
                    <Input {...lngProps} placeholder="请输入经度" />
                </FormItem>
                <FormItem label="纬度"
                    {...formItemLayout}
                          hasFeedback
                          help={isFieldValidating('lat') ? '校验中...' : (getFieldError('lat') || []).join(', ')}>
                    <Input {...latProps} placeholder="请输入纬度" />
                </FormItem>
            </Form>
        );
    }
}

// 合并机构
@Form.create()
class MergeOrg extends React.Component{
    constructor(props){
        super(props);
    }
    componentDidMount() {
        var {setFieldsValue} = this.props.form;
        // var jsondata=this.props.data;234w
        setFieldsValue( {merge_orgno:""});
    }
    render(){
        const formItemLayout={
            labelCol:{span:6},
            wrapperCol:{span:14}
        };
        const { getFieldProps, getFieldError, isFieldValidating } = this.props.form;
        const parentorgnoProps = getFieldProps('parentorgno', {
            rules: [
                { required: true, min: 0, message: '请选择上级机构' },
            ],
        });

        return(
            <Form horizontal>
                <FormItem label="合并到所属机构" {...formItemLayout}  >
                    <TreeSelectDemo {...parentorgnoProps} form={this.props.form} propsname="merge_orgno"  requestUrl="org010101.json" operation={this.props.operation}></TreeSelectDemo>
                </FormItem>
            </Form>
        );
    }
}

class FuncTree extends React.Component{
    constructor(props){
        super(props);
        //const keys = this.props.keys;

        console.log(menus);
        const keys= ['0-0-0', '0-0-1'];
        this.state={
            defaultExpandedKeys:keys,
            defaultSelectedKeys:keys,
            defaultCheckedKeys:keys,
            nodetree:[]
        };
    }
    onExpand(treeNode, expand, expandedKeys) {
        console.log('onExpand', expand, expandedKeys);
    }
    onSelect(info) {
        console.log('selected5', info);
    }
    onCheck(info) {
        console.log('onCheck123', info);
        this.props.treeOnCheck(info);
    }
    getTreeDom(childlist){
        if(!childlist){
            return;
        }
        let list=[];

        for(let i=0 ;i<childlist.length;i++){
            console.log("treekey"+childlist[i].id);
            list.push(<TreeNode title={childlist[i].text} key={childlist[i].id} >
                {this.getTreeDom(childlist[i].children)}
            </TreeNode>);
        }
        return list;
    }
    render(){
        return(
            <Tree className="myCls" showLine multiple checkable
                  defaultExpandedKeys={this.state.defaultExpandedKeys}
                  onExpand={this.onExpand}
                  defaultSelectedKeys={this.state.defaultSelectedKeys}
                  defaultCheckedKeys={this.state.defaultCheckedKeys}
                  onSelect={this.onSelect} onCheck={this.onCheck.bind(this)}>
                {this.getTreeDom(menus)}
            </Tree>
        );
    }
}



function generateTreeNodes(treeNode) {
    const arr = [];
    const key = treeNode.props.eventKey;
    console.log("treenodekey:"+key);
    for (let i = 0; i < 3; i++) {
        arr.push({ name: `leaf ${key}-${i}`, key: `${key}-${i}` });
    }
    return arr;
}

function setLeaf(treeData, curKey, level) {
    const loopLeaf = (data, lev) => {
        const l = lev - 1;
        data.forEach((item) => {
            if ((item.key.length > curKey.length) ? item.key.indexOf(curKey) !== 0 :
                curKey.indexOf(item.key) !== 0) {
                return;
            }
            if (item.children) {
                loopLeaf(item.children, l);
            } else if (l < 1) {
                item.isLeaf = true;
            }
        });
    };
    loopLeaf(treeData, level + 1);
}

function getNewTreeData(treeData, curKey, child, level) {
    const loop = (data) => {
        // if (level < 1 || curKey.length - 3 > level * 2) return;
        data.forEach((item) => {
            var cukey=curKey.split(",")[0];
            var itemkey=item.orgid;
            if (cukey.indexOf(itemkey) === 0) {
                if (item.children) {
                    loop(item.children);
                } else {
                    item.children = child;
                }
            }
        });
    };
    loop(treeData);
    setLeaf(treeData, curKey, level);
}

const TreeSelectDemo = React.createClass({
    getInitialState() {
        return {
            treeData: [],
        };
    },
    componentDidMount() {
        util.httpRequest({type:"POST",url:this.props.requestUrl,params:{orgname:"",
            orgno:"","parentorgno":""},success:function(result){
            result.rows.forEach(function(i){
                if(i.isleaf=="true"){
                    i.isLeaf=true;
                }
                else{
                    i.isLeaf=false;
                }
            });

            console.log(result.rows);
            this.setState({
                treeData:result.rows
            });
        }.bind(this)});
    },
    onSelect(info,node) {
        console.log('selec', info);
        console.log(node);
    },
    onLoadData(treeNode) {
        return new Promise((resolve) => {
            const key = treeNode.props.eventKey;
            var orgno=key.split(",")[1];
            console.log("nodekey:"+key);
            util.httpRequest({type:"POST",url:this.props.requestUrl,params:{orgname:"",
                orgno:"","parentorgno":orgno},success:function(result){
                console.log("orgtree");
                console.log(result);
                if(result.rows){
                    result.rows.forEach(function(i){
                        if(i.isleaf=="true"){
                            i.isLeaf=true;
                        }
                        else{
                            i.isLeaf=false;
                        }
                    });

                    const treeData = [...this.state.treeData];
                    getNewTreeData(treeData, treeNode.props.eventKey, result.rows, 2);
                    console.log("总的树形图数据1");
                    console.log(treeData);
                    this.setState({ treeData });
                    resolve();
                }
            }.bind(this)});

        });
    },
    //dafasdfqwe
    render() {
        const {getFieldProps} =this.props.form;
        const loop = data => data.map((item) => {
            if (item.children) {
                return <TreeNode title={item.orgname} key={item.orgid+","+item.orgno}  value={item.orgno}>{loop(item.children)}</TreeNode>;
            }
            return <TreeNode title={item.orgname} key={item.orgid+","+item.orgno} isLeaf={item.isLeaf} value={item.orgno}  />;
        });
        const treeNodes = loop(this.state.treeData);
        return (
            <TreeSelect  disabled={this.props.operation=="edit"} {...getFieldProps('parentorgno')} onSelect={this.onSelect} loadData={this.onLoadData} style={{ width: '100%',minWidth:"250px" }}>
                {treeNodes}
            </TreeSelect>
        );
    },
});

export {Search,Edit,FuncTree,TreeSelectDemo,MergeOrg}